import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:recorder_wav/recorder_wav.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/progress_dialog.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<PracticeVoiceState> buildEffect() {
  return combineEffects(<Object, Effect<PracticeVoiceState>>{
    Lifecycle.initState: _onInit,
    PracticeVoiceAction.onVoiceAi: _onVoiceAi,
    PracticeVoiceAction.onSubmit: _onSubmit,
  });
}

void _onInit(Action action, Context<PracticeVoiceState> ctx) async {
  Future.delayed(Duration.zero, () async {
    // get token
    var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
    pr.show();
    HttpResult result =
        await Http.get("/correct/pub/api/third/aliyun/voice/gettoken.mvc");
    pr.hide();

    if (result.success) {
      ctx.dispatch(PracticeVoiceActionCreator.token(result.data['token']));
    } else {
      Util.alertFail(result, ctx.context);
    }
  });
}

void _onVoiceAi(Action action, Context<PracticeVoiceState> ctx) async {
  var filePath = action.payload;

  // 结束录音, 识别
  // POST /stream/v1/asr?appkey=23****f5&format=pcm&sample_rate=16000&enable_punctuation_prediction=true&enable_inverse_text_normalization=true HTTP/1.1
  // X-NLS-Token: 450372e4279******bcc2b3c793
  var url = 'http://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr';
  var sampleRate = 16000;
  final _param = {
    'appkey': 'ManJi0aLPMz2C30T',
    'format': 'pcm',
    'sample_rate': sampleRate,
    'enable_punctuation_prediction': false,
    'enable_inverse_text_normalization': false,
  };

  final _headers = {
    'X-NLS-Token': ctx.state.aliToken,
    'Host': 'nls-gateway.cn-shanghai.aliyuncs.com',
  };

  var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
  pr.show();
  HttpResult result = await Http.upload(url,
      query: _param, headers: _headers, filePath: filePath);
  pr.hide();

  if (result.success) {
    print(result.data);
    ctx.dispatch(PracticeVoiceActionCreator.doneVoiceAi(result.data));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _onSubmit(Action action, Context<PracticeVoiceState> ctx) async {
  String title = ctx.state.titleEditController.text;
  String content = ctx.state.contentEditController.text;
  var type = ctx.state.typeValue;
  var grade = ctx.state.gradeValue;
  var userInfo = ctx.state.userInfo;

  if (title.isEmpty) {
    Util.alert('标题不能为空', ctx.context);
    return;
  }

  if (content.length < 15) {
    Util.alert('内容不能过短', ctx.context);
    return;
  }

  if (type == null || type.isEmpty) {
    Util.alert('请选择文体类型', ctx.context);
    return;
  }

  if (grade == null || grade.isEmpty) {
    Util.alert('请选择年级', ctx.context);
    return;
  }

  if (!Util.canUseAi(userInfo)) {
    bool ok =
        await Util.showConfirmDialog('会员已过期', '您的会员已过期，点击[确认]去充值', ctx.context);
    if (ok == true) {
      // 跳转去支付
      Navigator.of(ctx.context).pushNamed(Nav.PAY);
    }
    return;
  }

  Navigator.of(ctx.context).pushNamed(
    Nav.WEB_PAGE,
    arguments: {
      'url': '/correct/pub/anyone/view/machine/review.mvc',
      'share': false,
      'done': '',
      'postData': {
        "title": title,
        "content": content,
        "grade": grade,
        "type": type
      }
    },
  );
}
